package com.xsound.dp15.bluetooothmonitor;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.ParcelUuid;
import android.os.Parcelable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import com.xsound.dp15.bluetooothmonitor.BtToolKit.BtTool;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

public class DebugActivity extends AppCompatActivity {

    private static final String DEBUGTAG = "DebugActivity-->>";
    private static final String DEBUGDEVICENAME = "devicename";
    private static final String DEBUGDEVICEADDR = "deviceaddr";
    private static final int CONEXCEPTION_WHAT=0x01;
    private static final int CONEXCEPTION_ARG=0x01;

    private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    private BluetoothAdapter mbluetoothAdapter = null;
    private AudioManager audioManager = null;
    private boolean boundflag = false;

    private BtBroadcastReceiver debugReceiver;
    private MyRecever myrecever;
    private IntentFilter filter=null;
    private Parcelable[] btuuidExtra=new Parcelable[0];

    private String devicename = "";
    private String deviceaddr = "";
    private ActionBar bar;
    private Button conButton;
    private Button sendButton;
    private Button conTypeButton;

    private TextView infoText;
    private EditText uuidEditText;
    private EditText txEditText;

    private BluetoothDevice remoteDevice = null;
    private Handler debugHandler = null;

    private BluetoothSocket clientSocket=null;
    private InputStream inputStream = null;
    private OutputStream outputStream = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_debug);
        conButton = (Button) findViewById(R.id.connectButton);
        sendButton = (Button) findViewById(R.id.sendButton);
        conTypeButton=(Button) findViewById(R.id.conTypeButton);
        infoText = (TextView) findViewById(R.id.infotextView);
        uuidEditText = (EditText) findViewById(R.id.uuidEditText);
        txEditText = (EditText) findViewById(R.id.txEditText);

        bar = getSupportActionBar();
        bar.setIcon(R.mipmap.ic_launcher);
        bar.setDisplayShowHomeEnabled(true);

        mbluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//        mbluetoothAdapter=(BluetoothAdapter)getSystemService(Context.BLUETOOTH_SERVICE);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        Intent intent = this.getIntent();
        Bundle bundle = intent.getExtras();
        devicename = bundle.getString(DEBUGDEVICENAME);
        deviceaddr = bundle.getString(DEBUGDEVICEADDR);
        bar.setSubtitle(devicename);

        remoteDevice = mbluetoothAdapter.getRemoteDevice(deviceaddr);

        boundflag = BtTool.boundStateToBlooean(remoteDevice.getBondState());

        debugHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

            }
        };

        debugReceiver=new BtBroadcastReceiver();
        myrecever=new MyRecever();
        filter=new IntentFilter(BluetoothDevice.EXTRA_UUID);
//        registerReceiver(debugReceiver, filter);
        registerReceiver(myrecever, filter);

        conButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String numinput = "";
                String conuuidstr = "0000";
                UUID conuuid = null;
                numinput = uuidEditText.getText().toString().trim();

                if (numinput != "") {
                    conuuidstr += numinput + "-0000-1000-8000-00805F9B34FB";
                    conuuid = UUID.fromString(conuuidstr);
                    new connectThread(conuuid).start();

                   /* try {
                        clientSocket = remoteDevice.createRfcommSocketToServiceRecord(conuuid);
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.i("蓝牙socket--->", "创建异常");
                        Toast.makeText(DebugActivity.this, "无法创建该socket", Toast.LENGTH_SHORT).show();
                    }*/
                }
            }
        });

        conTypeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
//        return super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.debug_action_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //    return super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case R.id.action_info:
                String infostr="";
                infostr=handleGetinfo(remoteDevice);
                infoText.setText(infostr);
                return true;
            case R.id.action_bound:
                handleBound(remoteDevice);
                return true;
            default:
                return true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        unregisterReceiver(debugReceiver);
        unregisterReceiver(myrecever);
    }

    private String  handleGetinfo(BluetoothDevice device) {
        StringBuffer uuidstr = new StringBuffer("该机信息:\n");
        Boolean fetchFlag=false;
        BluetoothClass deviceClass;
        ParcelUuid[] btUuids;
//        Parcelable[] btuuidExtra = new Parcelable[0];

        int deviceclass;
        int majorclass;

        List<UUID> remoteuuids=new ArrayList();
        List<String> remoteuuidstrs=new ArrayList();

        deviceClass = device.getBluetoothClass();
        deviceclass=deviceClass.getDeviceClass();
        majorclass=deviceClass.getMajorDeviceClass();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            uuidstr.append(BtTool.getBtTypeStr(device.getType()) + ",");
        }
        uuidstr.append(BtTool.getBtClass(deviceclass) + "\n");
        uuidstr.append("具有的UUID:"+"\n");

 /*       fetchFlag=device.fetchUuidsWithSdp();
        if (fetchFlag){
//            btuuidExtra=debugReceiver.uuidExtra;
        }*/

        try {
            Method method = device.getClass().getMethod("getUuids", new Class[0]);
            ParcelUuid[] phoneUuids = (ParcelUuid[]) method.invoke(device, new Object[]{});
            if (phoneUuids != null && phoneUuids.length>0) {
                for (ParcelUuid uuid : phoneUuids) {
                    Log.d(DEBUGTAG,  uuid.toString());
                    remoteuuids.add(uuid.getUuid());
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
            Log.e(DEBUGTAG, "getDeviceUuids() failed", e);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
            Log.e(DEBUGTAG, "getDeviceUuids() failed", e);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            Log.e(DEBUGTAG, "getDeviceUuids() failed", e);
        }

//        btUuids=device.getUuids();
        System.out.println(btuuidExtra.length);

      /*  if (btuuidExtra.length>0) {
            for (Parcelable uuid : btuuidExtra) {
                Log.d(DEBUGTAG+"UUID:", uuid.toString());
                remoteuuidstrs.add(uuid.toString());
            }
        }*/

        Iterator it = remoteuuids.iterator();
        while(it.hasNext()){
            System.out.println(it.next());
            uuidstr.append(it.next()+"\n");
        }
        uuidstr.append("蓝牙主设备类："+BtTool.getMajorClassStr(majorclass)+"\n");

        return uuidstr.toString();

    }

    private void handleBound(BluetoothDevice device) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            device.createBond();
        }
        /*try {
            BtTool.boundDevice(device);
        } catch (Exception e) {
            Log.e(DEBUGTAG, "绑定设备异常");
            e.printStackTrace();
        }*/
    }

    private  class MyRecever extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action){
                case BluetoothDevice.ACTION_UUID:
                    btuuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
                    break;
                default:
                    break;
            }
        }
    }

    private class connectThread extends Thread{
        UUID uuidstr=null;
        public connectThread(UUID uuid){
            this.uuidstr=uuid;
        }
        @Override
        public void run() {
            super.run();
            try {
                clientSocket=remoteDevice.createRfcommSocketToServiceRecord(uuidstr);
            } catch (IOException e){
                e.printStackTrace();
                Log.i("蓝牙socket--->", "创建异常");
                Toast.makeText(DebugActivity.this,"无法创建socket",Toast.LENGTH_SHORT).show();
            }
            try {
                clientSocket.connect();
            } catch (IOException e) {
                e.printStackTrace();
                Log.i("蓝牙socket--->", "连接异常");
                Message conmsg=debugHandler.obtainMessage();
                conmsg.what=CONEXCEPTION_WHAT;
                conmsg.arg1=CONEXCEPTION_ARG;
                conmsg.obj="无法连接到该服务";
                debugHandler.sendMessage(conmsg);
            }

        }
    }

}
